import api from '@/api'

let state = {
    shopCartInfo: []
};

let actions = {
    //获取购物车数据
    async getShopCart({ commit }) {
        let result = await api.reqShopCart();
        if (result.code == 200) {
            commit('GETSHOPCART', result.data);
        }
    },
    //添加到购物车
    async addToCart({ commit }, { skuId, skuNum }) {
        let result = await api.reqAddToCart({ skuId, skuNum });
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error('添加失败'));
        }
    }
};

let mutations = {
    GETSHOPCART(state, cartInfo) {
        state.shopCartInfo = cartInfo;
    }
};

let getters = {
    cartInfo(state) {
        return state.shopCartInfo[0] || {};
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}